<template>
  <div class="app-container">
    <div class="card reserve-list__search">
      <el-form inline>
        <el-form-item label="会议室：">
          <el-select v-model="params.id" placeholder="请选择会议室" clearable>
            <el-option
              v-for="item in conferenceRoomList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态：">
          <el-select v-model="params.state" placeholder="请选择审核状态" clearable>
            <el-option label="审核成功" value="success" />
            <el-option label="审核失败" value="reject" />
            <el-option label="待审核" value="wait" />
            <el-option label="已撤销" value="revoke" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间：">
          <el-date-picker
            v-model="params.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="handleTimeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="card">
      <!--      <div style="padding: 0 0 20px 0;">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          @click="handleWeeklyView"-->
      <!--        >-->
      <!--          会议室预约看板-->
      <!--        </el-button>-->
      <!--      </div>-->
      <el-table
        v-loading="loading"
        :data="list"
        border
        style="width: 100%"
        stripe
      >
        <el-table-column label="预约人" prop="user.username" align="center" />
        <el-table-column label="会议室" prop="room_name" align="center" />
        <el-table-column label="开始时间" prop="start_time" align="center" />
        <el-table-column label="结束时间" prop="end_time" align="center" />
        <el-table-column label="预约原因" prop="reason" align="center" />
        <el-table-column label="审核状态" align="center">
          <template slot-scope="{row}">
            <el-tag :type="getStateInfo(row.state).type">
              {{ getStateInfo(row.state).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" prop="created_at" align="center">
          <template v-slot="{ row }">
            {{ timeFormat(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="created_at" align="center">
          <template v-slot="{ row }">
            <el-button type="text" size="small" @click="handlerShow(row)">
              <i class="el-icon-view" /> 查看
            </el-button>

            <el-button
              v-if="editBtnVisible(row)"
              type="text"
              size="small"
              @click="handlerEdit(row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="reserve-list__page">
        <Pagination
          style="margin-top: 0; padding-bottom: 0;"
          :total="total"
          :page="params.page"
          :limit="params.paginate"
          @pagination="pagination"
        />
      </div>
    </div>

    <ReserveDetailDrawer
      :visible.sync="showReserveDetailDialogVisible"
      :record-id="currentId"
    />

    <ReserveEdit
      v-model="editReserveInfo"
      :visible.sync="reserveEditVisible"
      :confirm-loading="editBtnLoading"
      @confirm="handlerEditConfirm"
    />
  </div>
</template>

<script>
import { getReserveRecords, getConferenceRoomList, editReservation } from '@/api/conferenceRoom'
import Pagination from '@/components/Pagination/index.vue'
import { timeFormat } from '@/utils'
import ReserveDetailDrawer from '@/views/conferenceRoomAppointment/components/reserveList/ReserveDetailDrawer.vue'
import dayjs from 'dayjs'
import ReserveEdit from '@/views/conferenceRoomAppointment/components/reserveList/ReserveEdit.vue'

export default {
  name: 'ReserveList',
  components: { ReserveDetailDrawer, Pagination, ReserveEdit },
  data() {
    return {
      list: [],
      loading: false,
      total: 0,
      params: {
        page: 1,
        paginate: 10,
        id: null,
        state: null,
        time: []
      },
      timeFormat,
      conferenceRoomList: [],
      showReserveDetailDialogVisible: false,
      currentId: null,
      editReserveInfo: null,
      reserveEditVisible: false,
      editBtnLoading: false
    }
  },
  computed: {
    getStateInfo() {
      return (state) => {
        const stateMap = {
          1: { type: 'success', label: '审批成功' },
          0: { type: 'danger', label: '审批失败' },
          2: { type: 'info', label: '已撤销' },
          3: { type: 'warning', label: '待审批' }
        }
        return stateMap[state] || stateMap[3]
      }
    }
  },
  mounted() {
    this.getList()
    this.getConferenceRoomList()
  },
  methods: {
    async getConferenceRoomList() {
      try {
        const { data } = await getConferenceRoomList()
        this.conferenceRoomList = data
      } catch (error) {
        this.$message.error('获取会议室列表失败')
      }
    },
    async getList() {
      this.loading = true
      try {
        const { data } = await getReserveRecords({
          ...this.params,
          time: this.params.time && this.params.time.length ? JSON.stringify(this.params.time) : null
        })
        this.list = data.data.map(item => {
          const roomInfo = JSON.parse(item.room)
          return {
            ...item,
            room_name: roomInfo.name
          }
        })
        this.total = data.total
      } catch (error) {
        console.log('error --------->', error)
        this.$message.error('获取预约记录失败')
      } finally {
        this.loading = false
      }
    },
    pagination(page) {
      this.params.page = page.page
      this.params.paginate = page.limit
      this.getList()
    },
    handleSearch() {
      this.params.page = 1
      this.getList()
    },
    handleReset() {
      this.params.conference_room_id = null
      this.params.state = null
      this.params.time = []
      this.handleSearch()
    },
    handleTimeChange(val) {
      if (val && val.length === 2) {
        this.params.time = [
          val[0].split(' ')[0] + ' 00:00:00',
          val[1].split(' ')[0] + ' 23:59:59'
        ]
      }
    },

    handlerShow(row) {
      this.currentId = row.id
      this.showReserveDetailDialogVisible = true
    },
    editBtnVisible(row) {
      const state = row.state
      const startTime = row?.start_time
      if ((state === null || state === 1) && startTime > dayjs().format('YYYY-MM-DD HH:mm:ss')) return true
      return false
    },

    handlerEdit(row) {
      console.log('row --------->', row)
      this.editReserveInfo = {
        id: row.id,
        conference_room_id: row.conference_room_id, // 会议室id
        start_time: row.start_time, // 开始时间
        end_time: row.end_time, // 结束时间
        reason: row.reason, // 预约原因
        notes: row.notes, // 备注
        users: row.users ? JSON.parse(row.users) : [] // 需要通知的参会人
      }

      this.reserveEditVisible = true
    },

    handlerEditConfirm(e) {
      console.log('e --------->', e)
      this.editReservationFetch(e)
    },

    async editReservationFetch(data) {
      this.editBtnLoading = true
      try {
        const res = await editReservation(data)
        this.$message.success('修改成功')
        this.reserveEditVisible = false
        this.handleReset()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      } finally {
        this.editBtnLoading = false
      }
    },

    handleWeeklyView() {
      this.$router.push({
        name: 'weeklyView'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .reserve-list__search {
    margin-bottom: 20px;
    ::v-deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 20px;
      .el-form-item__label {
        font-weight: 400;
      }
    }
  }

  .reserve-list__page {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
